package com.tgy.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/***
 * @ClassName: BaseDao
 * @Description: 操作数据库的公共类
 * @Auther: 送一一块二向箔
 * @Date: 16:36 2021/12/9
 * @version : V1.0
 */
public class BaseDao {
    private static DataSource dataSource;
    static {
        try {
            InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("DatabaseConfig.yml");
            //InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  static DataSource getDatasource() {return dataSource;};

    /**
     * @Param 获得连接
     * @Description:
     * @auther: TangGuoyi
     * @date: 17:19 2021/12/9
     * @return:
     */
    public  static Connection getC() throws SQLException {return dataSource.getConnection();}

    /**
     * @description: 释放资源 --->使用DbUtils包下的DbUtils工具类提供的closeQuietly()方法
     */
    public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) {
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(connection);
        System.out.println("数据库关闭成功");
    }


    /*
    * 查询公共类
    * */
    /**
     * @Param 查询公共类
     * @Description:
     * @auther: TangGuoyi
     * @date: 17:24 2021/12/9
     * @return:
     */
    public static ResultSet execute(int type,Connection connection, String sql, Object[] params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params!=null){
            for (int i = 0; i < params.length; i++) {
                //setObject()占位符是从1开始，而数组是从0开始；
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        System.out.println("DruidDao>>查>>SQL :" + preparedStatement.toString());
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    /**
     * @Param 增删改工具类
     * @Description: 重载一下上面的方法
     * @auther: TangGuoyi
     * @date: 17:24 2021/12/9
     * @return:
     */
    public static int execute(Connection connection, String sql, Object[] params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject()占位符是从1开始，而数组是从0开始；
            preparedStatement.setObject(i + 1, params[i]);
        }
        System.out.println("DruidDao>>增删改>>SQL :" + preparedStatement.toString());
        return preparedStatement.executeUpdate();
    }
}
